from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.utils import get_current_active_user, Helper
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings


router = APIRouter(prefix='/code/relation', tags=['Code'])
module_name = '码管理模块 - 作废单'


def format_serial_counts(serial_start, serial_end):
    start = int(serial_start)
    end = int(serial_end)
    return end - start + 1


@router.get('/batchs', response_model=schemas.BaseApiListOut)
async def get_relation_batchs(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    code: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """
        码管理 批次关联列表
    """

    objs = CodeModel.TenantBatchRelation.with_('brand').with_('order').with_('theme')

    if code:
        objs = objs.where('code', code)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'batch_sn', 'like', f'%{keyword}%'
            ).or_where(
                'code', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('/batchs', response_model=schemas.BaseApiOut)
async def add_relation_batch(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    post: dict = Body(...)
):
    """
        添加批次关联
    """

    theme = CodeModel.TenantTemplate.where('theme_code', post['theme_code']).first()
    if theme is None:
        return schemas.BaseApiOut(code=1, message='此模板信息不存在')
    order = CodeModel.Order.where('batch_sn', post['batch_sn']).first()
    if order is None:
        return schemas.BaseApiOut(code=1, message='此批次生码单信息不存在')
    if order.status != 2:
        return schemas.BaseApiOut(code=1, message='非生码成功的生码单不能进行绑定关联')
    if order.company_code != theme.code or theme.code != post['code']:
        return schemas.BaseApiOut(code=1, message='非同一个商户的生码单和模板不能进行绑定关联')

    serial_start = post['serial_start']
    serial_end = post['serial_end']
    if post['relation_type'] == 1:
        # 整批关联
        if order.serial_status == 1:
            serial_start = order.serial_serial_start
            serial_end = order.serial_serial_end
    else:
        # 区间关联 区间判断是否在生码单内部
        if order.serial_status == 0:
            return schemas.BaseApiOut(code=1, message='此批次生码单无流水号码，不能进行区间绑定关联')
        if serial_start < order.serial_serial_start or serial_start > order.serial_serial_end or serial_end < order.serial_serial_start or serial_end > order.serial_serial_end:
            return schemas.BaseApiOut(code=1, message='此批次生码单流水号码区间与提交区间不匹配，不能进行区间绑定关联')

    # 判断此批次是否已经有关联数据
    if post['relation_type'] == 2:
        exists = CodeModel.TenantBatchRelation.where(
            'code', post['code']
        ).where(
            'batch_sn', post['batch_sn']
        ).where(
            lambda query: query.where(
                lambda q: q.where('serial_start', '<=', serial_start).where('serial_end', '>=', serial_start)
            ).or_where(
                lambda q: q.where('serial_start', '<=', serial_end).where('serial_end', '>=', serial_end)
            )
        ).first()
        if exists is not None:
            return schemas.BaseApiOut(code=1, message='流水区间重叠,不能进行区间绑定关联')

    try:
        obj = CodeModel.TenantBatchRelation.create(
            code=post['code'].lower(),
            theme_code=post['theme_code'],
            batch_sn=post['batch_sn'],
            relation_type=post['relation_type'],
            serial_start=serial_start,
            serial_end=serial_end,
            counts=order.counts if post['relation_type'] == 1 else format_serial_counts(serial_start, serial_end),
        )

        print('操作成功:', obj.fresh().id)
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.delete('/batchs/{id}', response_model=schemas.BaseApiOut)
async def delete_relation_batch(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int
):
    """
        删除批次关联
    """

    obj = CodeModel.TenantBatchRelation.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    try:
        obj.delete()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.get('/goods', response_model=schemas.BaseApiListOut)
async def get_relation_goods(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    code: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """
        码管理 商品关联列表
    """

    objs = OemModel.Good.with_('brand')

    if code:
        objs = objs.where('code', code)
    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'good_code', 'like', f'%{keyword}%'
            ).or_where(
                'title', 'like', f'%{keyword}%'
            ).or_where(
                'code', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    relations = CodeModel.TenantGoodRelation.with_('theme').where_in('good_code', [i.good_code for i in objs]).all()
    format_objs = {}
    for i in relations:
        format_objs[i.good_code] = i.theme

    for item in objs:
        item.theme_code = ''
        item.theme_name = ''
        item.theme_thumb = ''

        if item.good_code in format_objs.keys():
            item.theme_code = format_objs[item.good_code]['theme_code']
            item.theme_name = format_objs[item.good_code]['title']
            item.theme_thumb = format_objs[item.good_code]['thumb']

    return objs.serialize()


@router.post('/goods', response_model=schemas.BaseApiOut)
async def add_relation_good(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    post: dict = Body(...)
):
    """
        添加 商品关联
    """

    theme = CodeModel.TenantTemplate.where('theme_code', post['theme_code']).first()
    if theme is None:
        return schemas.BaseApiOut(code=1, message='此模板信息不存在')
    good = OemModel.Good.where('good_code', post['good_code']).first()
    if good is None:
        return schemas.BaseApiOut(code=1, message='此商品信息不存在')
    if good.code != theme.code:
        return schemas.BaseApiOut(code=1, message='非同一个商户的商品和模板不能进行绑定关联')

    try:
        obj = CodeModel.TenantGoodRelation.create(
            code=post['code'].lower(),
            theme_code=post['theme_code'],
            good_code=post['good_code'],
        )

        print('操作成功:', obj.fresh().id)
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.delete('/goods', response_model=schemas.BaseApiOut)
async def delete_relation_good(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: dict = Body(...),
):
    """
        删除 商品关联
    """

    obj = CodeModel.TenantGoodRelation.where('code', post['code']).where('good_code', post['good_code']).where('theme_code', post['theme_code']).first()
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    try:
        obj.delete()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}
